'use strict';

app.controller('acceptListCtrl', ['$scope', '$http', '$stateParams', '$rootScope', '$filter', '$location', '$timeout', 'lodash', function($scope, $http, $stateParams, $rootScope, $filter, $location, $timeout, lodash) {
    $rootScope.initBreadcrumb($scope.breadcrumb);
    $scope.breadcrumb.push("需求管理", '受理需求');
    $rootScope.initHeaderElements($scope.settings);
    var backUrl = {
        show: true,
        label: "返回",
        func: function() {
            $rootScope.backHistory();
        }
    }
    var saveBtn = {
        show: true,
        label: "保存",
        btnId: "saveAcceptBtn",
        func: function() {
            saveDemand();
        }
    }
    $scope.settings.btnEle.push(saveBtn);
    $scope.settings.btnEle.push(backUrl);

    $scope.hasAcceptData = [];
    $scope.isActive = null;
    $scope.info = {
        need: "",
        issueList: [],
    }

    getUserAcceptCount();
    getDataType();
    getAllUser();
    getAllUser("need_master");

    // 获取当前用户的受理数量
    function getUserAcceptCount() {
        var url = matrix_product_url +"/need/getAcceptAccountAndStatus?acceptAccount="+ getUserAccount() +"&status=ACCEPT";
        $http.get(url).success(function(result) {
            if(result.code == "0") {
                $scope.hasAcceptData = result.data.length ? result.data : [];
                $("#acceptNum").html("受理需求（" + (result.data.length || 0) + "）");
            } else {
                $rootScope.toasterErrorInfo("获取当前用户的受理数量错误！");
            }
        });
    }

    //点击需求
    $scope.clickItem = function(accept) {
        $scope.isActive = accept.id;
        getNeedDetails(accept.id);
    };

    // 获取需求详细信息
    function getNeedDetails(id) {
        var url = matrix_product_url + "/need/getNeeds?id=" + id;
        $http.get(url).success(function(result) {
            if (result.code == "0") {
                console.log("result =----"+JSON.stringify(result))
                if(result.data.length == 0) {
                    var allAcceptData = $scope.hasAcceptData;
                    if (allAcceptData.length > 0) {
                        lodash.remove(allAcceptData, {"id": id});
                        getUserAcceptCount();
                    }
                    lodash.remove($scope.hasAcceptData, { "id": id });
                    $scope.isActive = null;
                    $rootScope.toasterWarningInfo("需求已删除！");
                    return false;
                }
                $scope.info.need = result.data[0];
                $scope.info.need.sltSource = lodash.findWhere($scope.info.sources, { "key": $scope.info.need.source });
                $scope.info.need.lossPrevent={isChecked:$scope.info.need.reduceLoss>0?true:false},
                $scope.info.need.mayProfit={isChecked:$scope.info.need.profit>0?true:false},
                $scope.info.need.saveCost={isChecked:$scope.info.need.expectLowerCostList.length>0?true:false},
                $scope.info.need.sltCreator = {
                    "crtname": $scope.info.need.proposerName,
                    "realname": $scope.info.need.proposerName,
                    "account": $scope.info.need.proposerAccount
                };
                $scope.info.need.sltPdm = {
                    "crtname": $scope.info.need.followName,
                    "realname": $scope.info.need.followName,
                    "account": $scope.info.need.followAccount
                };
                // 部门评定人
                if($scope.info.need.deptChargeAccount) {
                    $scope.info.need.sltDepartment = {
                        "crtname": $scope.info.need.deptChargeName,
                        "realname": $scope.info.need.deptChargeName,
                        "account": $scope.info.need.deptChargeAccount
                    };
                } else {
                    if($rootScope.isUserCanOperateByRole("dept_charger")) {
                        var sltNeedMasterItem = lodash.findWhere($scope.info.needMasterList, {"account": getUserAccount()});
                        $scope.info.need.sltDepartment = sltNeedMasterItem || "";
                    }
                }

                if($scope.info.need.source=="CUSTOMER") {
                    //客户名
                    if ($scope.info.need.customerName && $scope.info.need.customerCode) {
                        $scope.info.need.customers = {show: true}
                        $scope.info.need.customers.selCustomer = {
                            crtname: $scope.info.need.customerCode + " " + $scope.info.need.customerName
                        }
                    }
                }else if($scope.info.need.source=="WORKERORDER") {
                    //工单号
                    if ($scope.info.need.ticketNumber) {
                        $scope.info.need.workOrder = {show: true,
                            ticketNumber: $scope.info.need.ticketNumber,
                            content: ticketed_url
                        }
                    }
                }else {
                    //需求部门
                    if ($scope.info.need.needDept) {

                        $scope.info.need.departments = {show: true}
                        var needDept = $scope.info.need.needDept;
                        var dept = config_need_departments.filter(function (a) {
                            return a.type==needDept;
                        })[0];
                        $scope.info.need.departments.selDepartment =dept
                    }
                }
                $scope.info.need.departmentTrain = $scope.info.need.deptTrain == "1" ? true : false;
                $scope.info.need.pdmIsReturn = $scope.info.need.isFallback == "1" ? true : undefined;
                $scope.info.need.isComplete = $scope.info.need.isComplete == "1" ? true : undefined;
                $scope.info.need.sltItemValue = $scope.info.need.otherPurposes || "";
                $scope.info.need.pdmEndDate = Date.parse(new Date());
                $scope.info.issueList = $scope.info.need.issues;
            } else {
                $rootScope.toasterErrorInfo("获取需求数据详情异常，请联系管理员！");
            }
        });
    };

    // 获取来源数据
    function getDataType() {
        $scope.info.sources = $rootScope.getSysConfigList('NEED_SOURCE');
        angular.forEach($scope.info.sources, function(source) {
            source.crtname = source.value;
            if ($scope.info.need.source == source.key) {
                $scope.info.need.sourceObj = source;
            }
        })
    };

    //删除需求
    $scope.removeItem = function(accept) {
        var url = matrix_product_url + "/need/saveNeed";
        var confirmParams = {
            "titleData": "提示",
            "bodyData": "确定取消受理需求【" + accept.title + "】吗？"
        };
        var need={"id":accept.id,"status":"NO_ACCEPT","acceptAccount": "", "acceptName": ""}
        $rootScope.confirmWindow(confirmParams, function(data) {
            if (data) {
                $http({
                    method: "post",
                    url: url,
                    data: JSON.stringify(need),
                    headers: { "Content-Type": "application/json" }
                }).success(function(result) {
                    if (result.code == "0") {
                        lodash.remove($scope.hasAcceptData, { "id": accept.id });
                        getUserAcceptCount()
                        $rootScope.toasterWarningInfo("删除成功！");
                        $scope.isActive = null;
                    } else {
                        $rootScope.toasterErrorInfo(result.desc);
                    }
                });
            }
        })
    };

    // 获取全部用户
    function getAllUser(type) {
        var url = beetle_auth_url + "/user/?token_id=" + getTokenId();
        // if(type) {
        //     url = url + "&role_name="+ type;
        // }
        $http.get(url).success(function(result) {
            if (result.success) {
                if (result.data) {
                    angular.forEach(result.data, function(data) {
                        data.crtname = data.realname;
                    });
                    if(type) {
                        $scope.needMasterList = result.data;
                    } else {
                        $scope.userList = result.data;
                    }
                } else {
                    $rootScope.toasterErrorInfo("获取用户数据错误！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.msg);
            }
        });
    }

    // 保存
    function saveDemand() {
        if($scope.isActive == null){
            $rootScope.toasterWarningInfo("请先选择需求!");
            return false;
        }
        var purpose = "";
        angular.forEach($scope.info.need.sltObj, function(obj) {
            purpose += obj.key + ($scope.info.need.sltObj.length == obj+1 ? "" : ",");
        });
        if(!$scope.info.need.title) {
            $rootScope.toasterWarningInfo("需求标题不能为空！");
            return false;
        }
        if(!$scope.info.need.sltSource) {
            $rootScope.toasterWarningInfo("需求来源不能为空！");
            return false;
        }
        if(!$scope.info.need.needDesc) {
            $rootScope.toasterWarningInfo("需求简述不能为空！");
            return false;
        }
        var postParams = $scope.info.need
        //客户
        if($scope.info.need.customers) {
            if ($scope.info.need.customers.selCustomer) {
                if ($scope.info.need.customers.selCustomer.crtname) {
                    var crtname = $scope.info.need.customers.selCustomer.crtname;
                    var split = crtname.split(" ");
                    postParams.customerCode = split[0];
                    postParams.customerName = split[1];``
                }
            }
        }
    //部门
    if ($scope.info.need.departments) {
      if ($scope.info.need.departments.selDepartment) {
        postParams.needDept = $scope.info.need.departments.selDepartment.type;
      }
    }

        //工单
        if($scope.info.need.workOrder){
            if($scope.info.need.workOrder.ticketNumber){
                postParams.ticketNumber=$scope.info.need.workOrder.ticketNumber
                postParams.ticketUrl=$scope.info.need.workOrder.content+$scope.info.need.workOrder.ticketNumber
            }
        }

        //需求分类
        if($scope.info.need.sltSource){
            postParams.source = $scope.info.need.sltSource.key
        }

        var needStatusArray = ["DEVING", "INTEGRATIONING", "PLANS", "LATED", "ONLINE", "CLOSED"];
        var isNotEditStatus = lodash.findIndex(needStatusArray, function(status) {
            return status == $scope.info.need.status;
        })
        if(isNotEditStatus == -1) {
            if(postParams.isFallback == 1) {
                postParams.status = "FALLBACK";
                $scope.info.issueList = [];
            } else {
                postParams.status = $scope.info.need.status ? $scope.info.need.status : "NO_ACCEPT";
            }
            if ($scope.info.issueList.length > 0) {
                postParams.status = $scope.info.need.status == "DEVING" ? "DEVING" : "CONFIRM";
            }
        } else {
            postParams.status = $scope.info.need.status;
        }
        if($scope.info.need.status != "FALLBACK") {
            var confirmMessage = "";
            if($scope.info.need.pdmIsReturn) {
                if($scope.info.need) {
                    if(!$scope.info.need.fallbackReason) {
                        $rootScope.toasterWarningInfo("回退原因不能为空！");
                        return false;
                    }
                }
                confirmMessage = "确定要回退需求吗？";
                if($scope.info.issueList.length > 0) {
                    confirmMessage = "回退需求的同时会删除用户故事，确定要回退需求吗？";
                }
                var confirmParams = {
                    "titleData": "提示",
                    "bodyData": confirmMessage
                };
                $rootScope.confirmWindow(confirmParams, function () {
                    saveParams(postParams);
                }, function() {
                    console.log("cancel");
                });
            } else {
                saveParams(postParams);
            }
        } else {
            saveParams(postParams);
        }

    };

    function saveParams(postParams) {
        $("#saveAcceptBtn").css("disabled", true);
        var url = matrix_product_url + "/need/saveNeed";
        $http({
            method: "post",
            url: url,
            data: JSON.stringify(postParams),
            headers: { "Content-Type": "application/json" }
        }).success(function(result) {
            if (result.code == "0") {
                if ($scope.info.issueList.length > 0) {
                    saveIssue();
                } else {
                    window.location.href = "#/app/need/list/"+ ($stateParams.accept || "") +"/"+ ($stateParams.appointAccept || "");
                    $rootScope.toasterSuccessInfo("保存成功！");
                }
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
            $("#saveAcceptBtn").css("disabled", false);
        });
    }

    // 保存issue
    function saveIssue() {
        var paramsArray = new Array();
        angular.forEach($scope.info.issueList, function(issue) {
            var issueItem = {
                "needId": $scope.info.need.id,
                "number": issue.number || "",
                "creatorAccount": getUserAccount(),
                "creatorName": getUserName(),
                "groupTag": issue.sltTagGroup || "",
                "user": issue.sltUser ? issue.sltUser.name : "",
                "toAccount": issue.sltToAccount ? issue.sltToAccount.account : "",
                "action": issue.action || "",
                "status": "NEW"
            };
            if (issue.id) {
                issueItem.id = issue.id;
            }
            paramsArray.push(issueItem);
        });
        var postParams = {
            "issues": paramsArray
        };
        var url = matrix_product_url + "/issue/saveIssues";
        $http({
            method: "post",
            url: url,
            data: JSON.stringify(postParams),
            headers: { "Content-Type": "application/json" }
        }).success(function(result) {
            if (result.code == "0") {
                window.location.href = "#/app/need/list/"+ ($stateParams.accept || "") +"/"+ ($stateParams.appointAccept || "");
                $rootScope.toasterSuccessInfo("保存成功！");
            } else {
                $rootScope.toasterErrorInfo(result.desc);
            }
            $("#saveAcceptBtn").css("disabled", false);
        });
    }
}]);